package com.sms.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DocServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
			   // create output stream from byte array in session
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String token = request.getParameter("token");
            String docType = request.getParameter("docType");
            String fileName = request.getParameter("fileName")+".xls";
            byte[] byteArray = (byte[]) request.getSession().getAttribute(token);
            System.err.println("byteArray : "+byteArray.length);
            if(byteArray!=null)
            	baos.write(byteArray);

//            String fileName = "report.xls";
            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate,post-check=0,pre-check=0");
            response.setHeader("Pragma", "public");
            if(docType.equalsIgnoreCase("pdf"))
            	response.setContentType("application/pdf");
            else if(docType.equalsIgnoreCase("excel"))
            	response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName );


            // content length is needed for MSIE
            response.setContentLength(baos.size());

            // write ByteArrayOutputStream to ServletOutputStream
            ServletOutputStream out = response.getOutputStream();
            baos.writeTo(out);
            out.flush();
			

	}
	
	public String decodeUrlDelimiters(String url) {
		if (url == null)
			return null;

		url = url.replaceAll( "%2F",";");
		url = url.replaceAll("%2F","/");
		url = url.replaceAll("%3A",":" );
		url = url.replaceAll("%3F","\\?" );
		url = url.replaceAll("%26","&" );
		url = url.replaceAll( "%3D","\\=");
		url = url.replaceAll("%2B","\\+" );
		url = url.replaceAll("%24","\\$" );
		url = url.replaceAll("%2C","," );
		url = url.replaceAll("%23","#" );
		url = url.replaceAll("%27","'" );
		url = url.replaceAll("%20"," " );

		return url;
	}


}
